var levelList=require("../../utils/level.js");
var common = require("../../utils/parts.js");
var resourceUrl = getApp().request("imgUrl");
var requestUrl = getApp().request("url");
var header = getApp().request("header");
var app = getApp().globalData;
var myRefitTxt=null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    headImgUrl: "",
    nickName: "",
    myRefitTxt:"我的改装宣言",
    newPoster:false,
    score:"",
    fightCar:"",
    resourceUrl: resourceUrl,
    carLevelStar:"",
    carLevelName:"",
    carName:"",
    partDetail:{
      isShow:false
    },
    car:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.myRefitTxt()
    //获取本地的昵称和头像
    var score = app.score;
    var levelArr = levelList.list;
    //console.log(score)
    var levelName=null;
    for (var i = 0; i < levelArr.length;i++){
      if (score >= parseInt(levelArr[i].min) && score <= parseInt(levelArr[i].max)){
        levelName = levelArr[i];
        break;
      }
    }
    console.log(levelName)
    this.setData({
      headImgUrl: app.avatarUrl,
      nickName: app.nickName,
      score: score,
      carLevelStar: levelName.img,
      carLevelName: levelName.name,
      car:app.car
    })
    this.loadPart();
    //车辆类型
    var carName = app.car_name;
    carName = carName == "" ? "SUV概念车" : carName;
    this.setData({
      carName: carName
    });
    console.log(app)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      console.log(app)
      this.setData({
        newPoster:false
      })
      wx.showShareMenu({
        withShareTicket: true
      });
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (option) {
    //var carNames = this.data.carName
    var fightCarTypeId = app.fightCarTypeId;
    
    return {
      title: getApp().shareTitle1() ,
      path: "/pages/openShare/openShare?shareId=" + app.session_key.userId + "&carTypeId=" + fightCarTypeId + "&shareRefitNum=" + myRefitTxt + "&carName=SUV概念车",
      success: (re) => {
        if (Object.keys(re).length == 1) {
          return
        }
        var ticket = re.shareTickets[0];
        wx.getShareInfo({
          shareTicket: ticket,
          success:function(Re){
            console.log(Re)
            var encryptedData = Re.encryptedData;
            var iv=Re.iv;
            //请求分享接口加次数
            wx.request({
              url: requestUrl + 'shareGroupAddDrawNum',
              method: "POST",
              data: { userId: app.session_key.userId, salt: app.session_key.salt, encryptedData: encryptedData,iv:iv},
              header: header,
              success:function(Res){
                console.log(Res);
                if (Res.data.code==200){
                  //当日剩余抽取次数减去一
                  var shareLeftN = app.shareLeftN;
                  shareLeftN--;
                  app.shareLeftN=shareLeftN;
                  //剩余抽取次数加3次
                  var drawLeftN = app.drawLeftN;
                  drawLeftN+=3;
                  app.drawLeftN=drawLeftN;
                } else if (Res.data.code == 401 || Res.data.code == 301 || Res.data.code == 302){
                  getApp().showModal("提交信息有误!")
                } else if (Res.data.code == 304) {
                  //getApp().showModal("解密错误!")
                  getApp().sessionKey()
                } else if (Res.data.code == 800) {
                  getApp().showModal(Res.data.data.msg);
                  wx.hideLoading();
                }
              }
            })
          }
        })
        
      }
    }
    
    
  },
  //点击生成海报
  btnNewPoster(){
    var that=this;
    this.setData({
      newPoster:true
    })
    //放5张固定图片的对象
    var storageImgArr1 = {};
    //获取车辆信息
    var fightCarTypeId = app.fightCarTypeId;
    var car = this.data.car;
    var fightCar = null;
    if (fightCarTypeId == 0) {
      fightCar = car[0];
    } else {
      // for (var i = 0; i < car.length; i++) {
      //   if (car[i].type == fightCarTypeId) {
      //     fightCar = car[i];
      //   }
      // }
      fightCar = car[0];
    }
    for (var val in fightCar) {
      if ((val == "b" || val == "c" || val == "g") && fightCar[val] == "") {
        fightCar[val] = "0";
      }
    }
    var imgArr = {};
    var carArr = ["c", "f", "b", "a", "d", "e", "g"];
    //计算要存储车件的长度
    var partsLength=0;
    for (var i = 0; i < carArr.length; i++) {
      if (fightCar[carArr[i]]) {
        partsLength++;
      }
    };
    //----c
    if (fightCar[carArr[0]]) {
      wx.getImageInfo({
        src: resourceUrl + "/main/parts/" + carArr[0] + "/" + fightCar[carArr[0]] + "_big.png",
        success: function (res) {
          imgArr[carArr[0]]=res.path;
          that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
          app.storageImgArr2 = imgArr;
          console.log(imgArr);
        }
      })
    };
    //----f
    if (fightCar[carArr[1]]) {
      wx.getImageInfo({
        src: resourceUrl + "/main/parts/" + carArr[1] + "/" + fightCar[carArr[1]] + "_big.png",
        success: function (res) {
          imgArr[carArr[1]] = res.path;
          that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
          app.storageImgArr2 = imgArr;
          console.log(imgArr);
        }
      })
    }
    //----b
    if (fightCar[carArr[2]]) {
      wx.getImageInfo({
        src: resourceUrl + "/main/parts/" + carArr[2] + "/" + fightCar[carArr[2]] + "_big.png",
        success: function (res) {
          imgArr[carArr[2]] = res.path;
          that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
          app.storageImgArr2 = imgArr;
          console.log(imgArr);
        }
      })
    }
    //----a
    if (fightCar[carArr[3]]) {
      wx.getImageInfo({
        src: resourceUrl + "/main/parts/" + carArr[3] + "/" + fightCar[carArr[3]] + "_big.png",
        success: function (res) {
          imgArr[carArr[3]] = res.path;
          that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
          app.storageImgArr2 = imgArr;
          console.log(imgArr);
        }
      })
    }
    //----d
    if (fightCar[carArr[4]]) {
      wx.getImageInfo({
        src: resourceUrl + "/main/parts/" + carArr[4] + "/" + fightCar[carArr[4]] + "_big.png",
        success: function (res) {
          imgArr[carArr[4]] = res.path;
          that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
          app.storageImgArr2 = imgArr;
          console.log(imgArr);
        }
      })
    }
    //----e
    if (fightCar[carArr[5]]) {
      wx.getImageInfo({
        src: resourceUrl + "/main/parts/" + carArr[5] + "/" + fightCar[carArr[5]] + "_big.png",
        success: function (res) {
          imgArr[carArr[5]] = res.path;
          that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
          app.storageImgArr2 = imgArr;
          console.log(imgArr);
        }
      })
    }
    //----g
    if (fightCar[carArr[6]]) {
      wx.getImageInfo({
        src: resourceUrl + "/main/parts/" + carArr[6] + "/" + fightCar[carArr[6]] + "_big.png",
        success: function (res) {
          imgArr[carArr[6]] = res.path;
          that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
          app.storageImgArr2 = imgArr;
          console.log(imgArr);
        }
      })
    }
    

    
    //转化图片生成海报使用
    wx.getImageInfo({
      src: resourceUrl + "/main/bg1.jpg",
      success: function (res) {
        storageImgArr1.img1 = res.path;
        app.storageImgArr1=storageImgArr1;
        that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
      }
    })
    wx.getImageInfo({
      src: resourceUrl + "/links/bg_poster2.png",
      success: function (res) {
        storageImgArr1.img2 = res.path;
        app.storageImgArr1=storageImgArr1;
        that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
      }
    })
    wx.getImageInfo({
      src: that.data.headImgUrl,
      success: function (res) {
        console.log(res)
        storageImgArr1.img3 = res.path;
        app.storageImgArr1=storageImgArr1;
        that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
      },
      fail:function(fail){
         console.log(fail)
      }
    })
    wx.getImageInfo({
      src: that.data.carLevelStar,
      success: function (res) {
        storageImgArr1.img4 = res.path;
        app.storageImgArr1=storageImgArr1;
        that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
      }
    })
    wx.getImageInfo({
      src: resourceUrl + "/links/bg_hat.png",
      success: function (res) {
        storageImgArr1.img5 = res.path;
        app.storageImgArr1=storageImgArr1;
        that.isNavigate(Object.keys(storageImgArr1).length, partsLength);
      }
    });
    //存保存按钮
    wx.getImageInfo({
      src: resourceUrl + "/links/btn_savePoster.png",
      success: function (res) {
        app.btnSave=res.path;
      }
    });
    //存返回按钮
    wx.getImageInfo({
      src: resourceUrl + "/links/bg_back.png",
      success: function (res) {
        app.btnBack=res.path;
      }
    });
    
    //我的宣言存起来下页用
    app.myRefitTxt=that.data.myRefitTxt;
  },
  //是否跳转海报页
  isNavigate(param1, param2){
    var storageImg2 = app.storageImgArr2;
    if (param1 == 5 && Object.keys(storageImg2).length == param2){
      setTimeout(function () {
        wx.navigateTo({
          url: '../poster/poster'
        });
      }, 1000);
    }
  },
  changeSentence(){
    this.myRefitTxt()
  },
  //我的宣言
  myRefitTxt(){
    var declaration = getApp().Refit();
    myRefitTxt = Math.floor(Math.random() * declaration.length);
    
    this.setData({
      myRefitTxt: declaration[myRefitTxt]
    });
  },
  //加载车件
  loadPart(){
    var fightCarTypeId = app.fightCarTypeId;
    var car = this.data.car;
    var fightCar=null;
    if (fightCarTypeId == 0) {
      fightCar = car[0];
    }else{
      // for(var i=0;i<car.length;i++){
      //   if (car[i].type == fightCarTypeId){
      //     fightCar = car[i]
      //   }
      // }
      fightCar = car[0]
      delete fightCar.score;
      delete fightCar.type;
    }
    this.setData({
      fightCar: fightCar
    })
    var fightCarMain = this.data.fightCar;
    for (var val in fightCarMain){
      if ((val == "b" || val == "c" || val == "g") && fightCarMain[val]==""){
        fightCarMain[val]="0";
      }
    }
    this.setData({
      fightCarMain: fightCarMain
    })
    //console.log(fightCar)
  },
  //点击弹出车件详情
  btnPartDetail(e){
    console.log(e.currentTarget.dataset.part);
    var partDataset = e.currentTarget.dataset.part;
    var fightCarParts = this.data.fightCar;
    var partDetail = fightCarParts[partDataset];   //具体车件详情名字
    if (partDetail.length<2){return}
    console.log(partDetail);
    var first = partDetail[0];  //类别
    var second = partDetail[1]; //星级
    var third = partDetail[2];  //颜色
    var baseAttribute = common.getBaseAttribute(first, second);   //基础属性
    var colorAddition = common.getColorAddition(third);           //颜色加成
    var colorSingle = "(" + common.color[third - 1] + ")";
    if (first == "a" || first == "h") {                        //颜色加成
      colorSingle = ""
    }
    //当是稀有配件时，单独处理
    var partName = null;
    if (first == "h") {
      partName = common[first][second][third].name;
    } else {
      partName = common[first][second].name + colorSingle;
    }
    if (first == "h" || first == "a") {
      colorAddition = 0;
    }
    var price = (baseAttribute * second + colorAddition) * 10;    //价格和评分一样
    console.log(partName + "------" + second+"++++++"+price);
    this.setData({
      "partDetail.isShow":true,
      "partDetail.infor":{
        partName: partName,
        star: second,
        partScore: price,
        imgUrl: partDetail
      }
    })
  },
  //关闭车件弹出详情
  btnClosePartDetail(){
    this.setData({
      "partDetail.isShow": false
      })
  }
})